<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>分类参数</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 卡片区域 -->
		<el-card>
			<!-- 警告区域 -->
			<el-alert title="注意：只允许为第三级分类设置相关的参数" type="warning" :closable="false" show-icon></el-alert>

			<!-- 选择商品分类区域 -->
			<el-row class="cat_opt">
				<el-col>
					<span>选择商品分类：</span>
					<!-- 选择商品分类的级联选择框 -->
					<el-cascader
						style="width:250px;"
						v-model="selectedKeys"
						:options="catelist"
						:props="propsList"
						@change="handleChange"
					></el-cascader>
				</el-col>
			</el-row>

			<!-- tabs页签标签栏 -->
			<el-tabs v-model="activeName" @tab-click="handleTabClick">
				<!-- 动态参数 -->
				<el-tab-pane label="动态参数" name="many">
					<el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数</el-button>
					<!-- 动态的表格 -->
					<el-table :data="manyTableData" border stripe>
						<el-table-column type="expand">
							<template v-slot="scope">
								<el-tag
									v-for="(item,i) in scope.row.attr_vals"
									:key="i"
									closable
									@close="handleClose(i,scope.row)"
								>{{item}}</el-tag>
								<!-- 添加的tag标签 -->
								<el-input
									class="input-new-tag"
									v-if="scope.row.inputVisible"
									v-model="scope.row.inputValue"
									ref="saveTagInput"
									size="small"
									@keyup.enter.native="handleInputConfirm(scope.row)"
									@blur="handleInputConfirm(scope.row)"
								></el-input>
								<el-button
									v-else
									class="button-new-tag"
									size="small"
									@click="showInput(scope.row)"
								>+ New Tag</el-button>
							</template>
						</el-table-column>
						<el-table-column type="index"></el-table-column>
						<el-table-column label="参数名称" prop="attr_name"></el-table-column>
						<el-table-column label="操作">
							<template v-slot="scope">
								<el-button
									type="primary"
									icon="el-icon-edit"
									size="mini"
									@click="showEditDialog(scope.row.attr_id)"
								>编辑</el-button>
								<el-button
									type="danger"
									icon="el-icon-delete"
									size="mini"
									@click="removeParams(scope.row.attr_id)"
								>删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<!-- 静态属性 -->
				<el-tab-pane label="静态属性" name="only">
					<el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性</el-button>
					<el-table :data="onlyTableData" border stripe>
						<el-table-column type="expand">
							<template v-slot="scope">
								<el-tag
									v-for="(item,i) in scope.row.attr_vals"
									:key="i"
									closable
									@close="handleClose(i,scope.row)"
								>{{item}}</el-tag>
								<!-- 添加的tag标签 -->
								<el-input
									class="input-new-tag"
									v-if="scope.row.inputVisible"
									v-model="scope.row.inputValue"
									ref="saveTagInput"
									size="small"
									@keyup.enter.native="handleInputConfirm(scope.row)"
									@blur="handleInputConfirm(scope.row)"
								></el-input>
								<el-button
									v-else
									class="button-new-tag"
									size="small"
									@click="showInput(scope.row)"
								>+ New Tag</el-button>
							</template>
						</el-table-column>
						<el-table-column type="index"></el-table-column>
						<el-table-column label="属性名称" prop="attr_name"></el-table-column>
						<el-table-column label="操作">
							<template v-slot="scope">
								<el-button
									type="primary"
									icon="el-icon-edit"
									size="mini"
									@click="showEditDialog(scope.row.attr_id)"
								>编辑</el-button>
								<el-button
									type="danger"
									icon="el-icon-delete"
									size="mini"
									@click="removeParams(scope.row.attr_id)"
								>删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
			</el-tabs>

			<!-- dialog对话框 -->
			<!-- 添加参数/属性 对话框 -->
			<el-dialog
				:title="activeName=='many'?'添加动态参数':'添加静态属性'"
				:visible.sync="addDialogVisible"
				width="50%"
				@close="addDialogClosed"
			>
				<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="130px">
					<el-form-item :label="activeName=='many'?'添加动态参数':'添加静态属性'" prop="attr_name">
						<el-input v-model="addForm.attr_name"></el-input>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
					<el-button @click="addDialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="addParams">确 定</el-button>
				</span>
			</el-dialog>
			<!-- 编辑参数 对话框 -->
			<el-dialog
				:title="activeName=='many'?'修改动态参数':'修改静态属性'"
				:visible.sync="editDialogVisible"
				width="50%"
				@close="editDialogClosed"
			>
				<el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="130px">
					<el-form-item :label="activeName=='many'?'修改动态参数':'修改静态属性'" prop="attr_name">
						<el-input v-model="editForm.attr_name"></el-input>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
					<el-button @click="editDialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="editParams">确 定</el-button>
				</span>
			</el-dialog>
		</el-card>
	</div>
</template>
<script>
export default {
	data() {
		return {
			//渲染这个里面的级联结构
			catelist: [],
			//绑定的一些属性配置
			propsList: {
				expandTrigger: 'hover',
				value: 'cat_id',
				label: 'cat_name',
				children: 'children'
			},
			//v-model把选中的value值双向绑定到这个selectedKeys数组中
			selectedKeys: [],
			activeName: 'many',
			manyTableData: [],
			onlyTableData: [],
			addDialogVisible: false,
			addForm: {
				attr_name: ''
			},
			addFormRules: {
				attr_name: [
					{
						required: true,
						message: '请输入信息',
						trigger: 'blur'
					},
					{
						min: 1,
						max: 10,
						message: '长度在 1 到 10 个字符',
						trigger: 'blur'
					}
				]
			},
			editDialogVisible: false,
			editForm: {
				attr_name: ''
			},
			editFormRules: {
				attr_name: [
					{
						required: true,
						message: '请输入信息',
						trigger: 'blur'
					},
					{
						min: 1,
						max: 10,
						message: '长度在 1 到 10 个字符',
						trigger: 'blur'
					}
				]
			}
		}
	},
	created() {
		this.getCateList()
	},
	computed: {
		isBtnDisabled() {
			if (this.selectedKeys.length !== 3) {
				return true
			}
			return false
		},
		cateId: function() {
			if (this.selectedKeys.length === 3) {
				return this.selectedKeys[2]
			}
			return null
		}
	},
	methods: {
		async getCateList() {
			//获得所有商品分类信息
			const { data: res } = await this.$http.get('categories')
			if (res.meta.status !== 200)
				return this.$message.error({
					message: res.meta.msg,
					offset: 100
				})
			this.catelist = res.data
		},
		async handleChange() {
			this.getParamsDate()
		},
		handleTabClick() {
			//tab页签点击事件的处理
			this.getParamsDate()
		},
		async getParamsDate() {
			if (this.selectedKeys.length !== 3) {
				this.selectedKeys = []
				this.manyTableData = []
				this.onlyTableData = []
				return
			}

			const { data: res } = await this.$http.get(
				`categories/${this.cateId}/attributes`,
				{
					params: { sel: this.activeName }
				}
			)
			if (res.meta.status !== 200)
				return this.$message.error({
					message: res.meta.msg,
					offset: 100
				})
			res.data.forEach(item => {
				//item.attr_vals为空就返回空数组
				item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
				item.inputVisible = false
				item.inputValue = ''
			})

			if (this.activeName === 'many') {
				this.manyTableData = res.data
			} else {
				this.onlyTableData = res.data
			}
		},
		addDialogClosed() {
			this.$refs.addFormRef.resetFields()
		},
		addParams: function() {
			//dialog对话框确定按钮
			this.$refs.addFormRef.validate(async valid => {
				if (!valid) {
					return
				}
				//发起添加用户请求
				const { data: res } = await this.$http.post(
					`categories/${this.cateId}/attributes`,
					{
						attr_name: this.addForm.attr_name,
						attr_sel: this.activeName
					}
				)
				if (res.meta.status !== 201) {
					return this.$message.error({
						message: res.meta.msg,
						offset: 100
					})
				}
				this.$message.success({ message: res.meta.msg, offset: 100 })
				this.addDialogVisible = false
				this.getParamsDate()
			})
		},
		async showEditDialog(attr_id) {
			//点击编辑按钮
			const { data: res } = await this.$http.get(
				`categories/${this.cateId}/attributes/${attr_id}`,
				{
					params: { attr_sel: this.activeName }
				}
			)
			if (res.meta.status !== 200) {
				return this.$message.error({
					message: res.meta.msg,
					offset: 100
				})
			}
			this.editForm = res.data
			this.editDialogVisible = true
		},
		editDialogClosed() {
			//编辑的对话框关闭事件
			this.$refs.editFormRef.resetFields()
		},
		editParams() {
			//编辑对话框的确定按钮 事件
			this.$refs.editFormRef.validate(async valid => {
				if (!valid) {
					return
				}
				//发起添加用户请求
				const { data: res } = await this.$http.put(
					`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
					{
						attr_name: this.editForm.attr_name,
						attr_sel: this.activeName
					}
				)
				if (res.meta.status !== 200) {
					return this.$message.error({
						message: res.meta.msg,
						offset: 100
					})
				}
				this.$message.success({ message: res.meta.msg, offset: 100 })
				this.getParamsDate()
				this.editDialogVisible = false
			})
		},
		async removeParams(attr_id) {
			//删除按钮的事件
			const confirmResult = await this.$confirm(
				'此操作将永久删除该参数, 是否继续?',
				'提示',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			).catch(err => err)

			if (confirmResult !== 'confirm') {
				return this.$message.info({
					message: '已取消删除',
					offset: 100
				})
			}
			const { data: res } = await this.$http.delete(
				`categories/${this.cateId}/attributes/${attr_id}`
			)
			if (res.meta.status !== 200) {
				return this.$message.error({
					message: res.meta.msg,
					offset: 100
				})
			}
			this.$message.success({ message: res.meta.msg, offset: 100 })
			this.getParamsDate()
		},
		async handleInputConfirm(row) {
			//添加的tag的事件
			if (row.inputValue.trim().length === 0) {
				row.inputValue = ''
				row.inputVisible = false
				return
			}
			row.attr_vals.push(row.inputValue.trim())
			row.inputValue = ''
			const { data: res } = await this.$http.put(
				`categories/${this.cateId}/attributes/${row.attr_id}`,
				{
					attr_name: row.attr_name,
					attr_sel: row.attr_sel,
					attr_vals: row.attr_vals.join(' ')
				}
			)
			if (res.meta.status !== 200)
				return this.$message.error({
					message: res.meta.msg,
					offset: 100
				})
			this.$message.success({
				message: res.meta.msg,
				offset: 100
			})

			row.inputVisible = false
		},
		showInput(row) {
			row.inputVisible = true
			//$nextTick的作用：当页面上元素被重新渲染之后才执行
			this.$nextTick(_ => {
				this.$refs.saveTagInput.$refs.input.focus()
			})
		},
		async handleClose(i, row) {
			//tag标签关闭事件
			row.attr_vals.splice(i, 1)
			const { data: res } = await this.$http.put(
				`categories/${this.cateId}/attributes/${row.attr_id}`,
				{
					attr_name: row.attr_name,
					attr_sel: row.attr_sel,
					attr_vals: row.attr_vals.join(' ')
				}
			)
			if (res.meta.status !== 200)
				return this.$message.error({
					message: res.meta.msg,
					offset: 100
				})
			this.$message.success({
				message: res.meta.msg,
				offset: 100
			})
		}
	}
}
</script>
<style lang="less" scoped>
.cat_opt {
	margin: 15px 0;
}
.el-tag {
	margin: 0 10px;
}
.el-input {
	width: 120px;
}
</style>